// API配置
const API_BASE_URL = 'http://snake.ipvv.net/api';

// 获取token
function getAuthToken() {
    return localStorage.getItem('token');
}

// 设置token
function setAuthToken(token) {
    localStorage.setItem('token', token);
}

// 清除token
function clearAuthToken() {
    localStorage.removeItem('token');
}

// 通用API调用
async function apiCall(endpoint, options = {}) {
    const token = getAuthToken();
    const headers = {
        'Content-Type': 'application/json',
        ...options.headers
    };
    
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}${endpoint}`, {
            ...options,
            headers
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        console.error('API调用失败:', error);
        throw error;
    }
}

// 用户登录
async function login() {
    const username = document.getElementById('loginUsername').value.trim();
    const password = document.getElementById('loginPassword').value.trim();
    
    if (!username || !password) {
        alert('请输入用户名和密码');
        return;
    }
    
    try {
        const response = await apiCall('/auth/login', {
            method: 'POST',
            body: JSON.stringify({ username, password })
        });
        
        setAuthToken(response.token);
        updateUIAfterLogin(response.username, response.highestScore);
        
        // 清空表单
        document.getElementById('loginUsername').value = '';
        document.getElementById('loginPassword').value = '';
        
        alert('登录成功！');
    } catch (error) {
        alert('登录失败：' + error.message);
    }
}

// 用户注册
async function register() {
    const username = document.getElementById('registerUsername').value.trim();
    const password = document.getElementById('registerPassword').value.trim();
    
    if (!username || !password) {
        alert('请输入用户名和密码');
        return;
    }
    
    if (username.length < 3 || username.length > 20) {
        alert('用户名长度必须在3-20个字符之间');
        return;
    }
    
    if (password.length < 6) {
        alert('密码长度至少为6个字符');
        return;
    }
    
    try {
        const token = getAuthToken();
        const headers = {
            'Content-Type': 'application/json',
            ...(token && { 'Authorization': `Bearer ${token}` })
        };
        
        const response = await fetch(`${API_BASE_URL}/auth/register`, {
            method: 'POST',
            headers,
            body: JSON.stringify({ username, password })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        // 尝试解析JSON，如果失败则忽略
        try {
            await response.json();
        } catch (jsonError) {
            // 忽略JSON解析错误
            console.log('注册成功（非JSON响应）');
        }
        
        // 清空表单
        document.getElementById('registerUsername').value = '';
        document.getElementById('registerPassword').value = '';
        
        alert('注册成功！请登录');
        showLogin();
    } catch (error) {
        alert('注册失败：' + error.message);
    }
}

// 用户退出登录
function logout() {
    clearAuthToken();
    updateUIAfterLogout();
    alert('已退出登录');
}

// 保存游戏结果
async function saveGameResult(score) {
    try {
        await apiCall('/game/result', {
            method: 'POST',
            body: JSON.stringify({
                score: score,
                durationSeconds: Math.floor(Math.random() * 300) + 60,
                levelReached: Math.floor(score / 100) + 1
            })
        });
        
        // 更新最高分
        await updateUserInfo();
        
        // 刷新排行榜
        loadLeaderboard();
    } catch (error) {
        console.error('保存游戏结果失败:', error);
    }
}

// 获取用户信息
async function getUserInfo() {
    try {
        const response = await apiCall('/user/profile');
        return response;
    } catch (error) {
        console.error('获取用户信息失败:', error);
        throw error;
    }
}

// 获取排行榜
async function getLeaderboard() {
    try {
        const response = await apiCall('/user/top-users');
        return response;
    } catch (error) {
        console.error('获取排行榜失败:', error);
        throw error;
    }
}

// 更新UI登录后状态
function updateUIAfterLogin(username, highestScore) {
    document.getElementById('authSection').style.display = 'none';
    document.getElementById('userInfo').style.display = 'flex';
    document.getElementById('currentUsername').textContent = username;
    document.getElementById('highestScore').textContent = highestScore;
    document.getElementById('gameHighestScore').textContent = highestScore;
    
    localStorage.setItem('highestScore', highestScore);
}

// 更新UI退出登录状态
function updateUIAfterLogout() {
    document.getElementById('authSection').style.display = 'block';
    document.getElementById('userInfo').style.display = 'none';
    document.getElementById('currentUsername').textContent = '';
    document.getElementById('highestScore').textContent = '0';
    document.getElementById('gameHighestScore').textContent = '0';
    
    localStorage.setItem('highestScore', '0');
}

// 更新用户信息
async function updateUserInfo() {
    try {
        const userInfo = await getUserInfo();
        document.getElementById('highestScore').textContent = userInfo.highestScore;
        document.getElementById('gameHighestScore').textContent = userInfo.highestScore;
        localStorage.setItem('highestScore', userInfo.highestScore);
    } catch (error) {
        console.error('更新用户信息失败:', error);
    }
}

// 加载排行榜
async function loadLeaderboard() {
    try {
        const leaderboard = await getLeaderboard();
        const leaderboardList = document.getElementById('leaderboardList');
        
        if (leaderboard.length === 0) {
            leaderboardList.innerHTML = '<p>暂无数据</p>';
            return;
        }
        
        leaderboardList.innerHTML = leaderboard
            .slice(0, 10)
            .map((user, index) => `
                <div class="leaderboard-item">
                    <span class="leaderboard-rank">#${index + 1}</span>
                    <span class="leaderboard-name">${user.username}</span>
                    <span class="leaderboard-score">${user.highestScore}</span>
                </div>
            `).join('');
    } catch (error) {
        console.error('加载排行榜失败:', error);
        document.getElementById('leaderboardList').innerHTML = '<p>加载失败</p>';
    }
}

// 检查登录状态
async function checkLoginStatus() {
    const token = getAuthToken();
    if (!token) {
        updateUIAfterLogout();
        return;
    }
    
    try {
        const userInfo = await getUserInfo();
        updateUIAfterLogin(userInfo.username, userInfo.highestScore);
    } catch (error) {
        console.error('检查登录状态失败:', error);
        clearAuthToken();
        updateUIAfterLogout();
    }
}

// 切换登录/注册表单
function showLogin() {
    document.getElementById('loginForm').style.display = 'block';
    document.getElementById('registerForm').style.display = 'none';
}

function showRegister() {
    document.getElementById('loginForm').style.display = 'none';
    document.getElementById('registerForm').style.display = 'block';
}

// 页面加载完成后检查登录状态
window.addEventListener('load', () => {
    checkLoginStatus();
    loadLeaderboard();
});
